<?php

namespace app\admin\model;

use johnxu\tool\Hash;
use johnxu\tool\Str;
use think\Db;
use think\Model;

class Users extends Model
{
    protected $name               = 'users';
    protected $insert             = [ 'uid', 'nickname', 'avatar' => '/static/admin/img/avatar.png' ];
    protected $autoWriteTimestamp = true;
    protected $createTime         = 'create_at';
    protected $updateTime         = 'update_at';

    /**
     * 获取客户分组对应列表
     *
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserList()
    {
        return Db::view( 'users', '*' )
            ->view( 'users_group', 'group_id', 'users.id=users_group.users_id', 'left' )
            ->view( 'group', 'title', 'group.id=users_group.group_id', 'left' )
            ->where( 'users.type', 'service' )
            ->select();
    }

    /**
     * 设置昵称
     *
     * @param $value
     * @param $data
     *
     * @return mixed
     */
    protected function setNicknameAttr( $value, $data )
    {
        return $data['username'];
    }

    /**
     * 编号
     *
     * @return string
     * @throws \Exception
     */
    protected function setUidAttr()
    {
        return 'u' . strtolower( Str::instance()->getMachineCode( 1, 16 ) );
    }

    protected function setPasswordAttr( $value )
    {
        return Hash::make( $value );
    }

    /**
     * 登录
     *
     * @param string $username
     * @param string $password
     *
     * @return bool|mixed
     */
    public static function login( string $username, string $password )
    {
        if ( !$username || !$password )
        {
            return false;
        }
        $result = self::get( [ 'username' => $username ] );
        if ( $result && Hash::check( $password, $result['password'] ) )
        {
            // 处理登录逻辑
            session( 'auth_user', $result );

            return $result;
        }

        return false;
    }
}
